import React, {useState} from 'react';
import ReactDOM from 'react-dom';
import { makeStyles, withStyles } from '@material-ui/core';
import Box from '@mui/material/Box';
import Button from "@material-ui/core/Button";
import Recorder from "recorder-core";
import PCMPlayer from "pcm-player";

//需要使用到的音频格式编码引擎的js文件统统加载进来
import "recorder-core/src/engine/mp3";
import "recorder-core/src/engine/mp3-engine";

//以上三个也可以合并使用压缩好的recorder.xxx.min.js
//比如 import Recorder from 'recorder-core/recorder.mp3.min' //已包含recorder-core和mp3格式支持

//可选的扩展支持项
import "recorder-core/src/extensions/wavesurfer.view";
import {Alert} from "@material-ui/lab";
import Snackbar from "@material-ui/core/Snackbar";

const useStyles = {
    textField: {
        marginLeft: '10px',
        marginRight: '10px',
        width: 300,
    },
    outsideContainer:{
        height: "100%",
        width: "100%",
        //border: "3px solid #9A14E1"
    }
};

class MyPlayer extends React.Component {
    constructor(props) {
        super(props)
        this.handlePlay = this.handlePlay.bind(this)
        this.showAlert = this.showAlert.bind(this);
        this.state = {
            ws: null,
            player: null,
            src: "",
            wave: null,
            connected: false,
            open: false,
            message: "",
            alertType: "error",
            listening: false
        }
    }

    componentDidMount() {
        this.$el = ReactDOM.findDOMNode(this)
        this.$waveform = this.$el.querySelector('.wave')
        console.log(this.$waveform)

        this.state.player = new PCMPlayer({
            encoding:"16bitInt",
            channels:1,
            sampleRate:8000,
            flushTime:2000
        })
        var set = {
            elem: this.$waveform,

            scale: 2, //缩放系数，应为正整数，使用2(3? no!)倍宽高进行绘制，避免移动端绘制模糊

            fps: 50, //绘制帧率，不可过高，50-60fps运动性质动画明显会流畅舒适，实际显示帧率达不到这个值也并无太大影响

            duration: 2500, //当前视图窗口内最大绘制的波形的持续时间，此处决定了移动速率
            direction: 1, //波形前进方向，取值：1由左往右，-1由右往左
            position: 0, //绘制位置，取值-1到1，-1为最底下，0为中间，1为最顶上，小数为百分比

            centerHeight: 1, //中线基础粗细，如果为0不绘制中线，position=±1时应当设为0

            //波形颜色配置：[位置，css颜色，...] 位置: 取值0.0-1.0之间
            linear: [
                0,
                "rgba(0,187,17,1)",
                0.7,
                "rgba(255,215,0,1)",
                1,
                "rgba(255,102,0,1)"
            ],
            centerColor: "" //中线css颜色，留空取波形第一个渐变颜色
        };
        this.state.wave = Recorder.WaveSurferView(set);
    }
    handlePlay() {
        //let url = "ws://8.131.62.53:8088/api/connws"; //替换成自己的websocket地址
        let url = "ws://localhost:8088/api/connws"; //替换成自己的websocket地址
        this.state.ws = new WebSocket(url);
        this.state.ws.binaryType = "arraybuffer";
        let _this = this;


        this.state.ws.addEventListener("open", function() {
            let jsonData = { state: "start", channel: "1" };
            _this.state.ws.send(JSON.stringify(jsonData));
            _this.showAlert("success", "连接Websocket成功");
        });
        this.state.ws.addEventListener("message", function(event) {
            console.log(event.data);
            let dataAudio = new Uint8Array(event.data);
            if (_this.state.listening === true) {
                _this.state.player.feed(dataAudio) // 播放
                let data = new Uint16Array(event.data);
                _this.state.wave.input(data, 20, 32000); // 画
            }
        });
    }

    showAlert = (type, msg) => {
        this.setState({
            alertType: type,
            connected: true,
            message: msg,
            open: true,
        })
        let _this = this;
        setTimeout(() => {
            _this.setState({
                open: false
            })
        }, 2000);
    }

    render() {
        const { classes } = this.props;
        let _this = this

        function Buttons() {
            //<---->
            function startListening() {
                _this.setState({
                    listening: !_this.state.listening
                })
                let msg = _this.state.listening === false ? '已开始监听' : '已停止监听';
                _this.showAlert("success", msg)
                console.log("startListening")
            }

            const ButtonStyles = makeStyles({
                outsideContainer:{
                    height: "100%",
                    width: "100%",
                    //border: "2px solid black",
                    display: "flex"
                },
                itemStyle:{
                    border: "1px solid #AEAEAE",
                    borderRadius: 10,
                    marginTop: 20,
                    width: 160,
                    marginLeft: 15,
                    height: 40,
                    backgroundColor: "#FFFFFF",
                    display: "flex",
                    /*实现垂直居中*/
                    alignItems: "center",
                    /*实现水平居中*/
                    justifyContent: "center",
                    fontWeight:"bold"
                }
            });
            const buttonStyle = ButtonStyles();
            return (
                <Box className={buttonStyle.outsideContainer}>
                    <Button className={buttonStyle.itemStyle} onClick={_this.handlePlay}>连接服务器</Button>
                    <Button className={buttonStyle.itemStyle} onClick={startListening}>
                        {_this.state.listening === true ? '停止监听' : '开始监听'}
                    </Button>
                </Box>
            );
        }

        return (
            <Box className={classes.outsideContainer}>
                <Snackbar
                    anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
                    open={this.state.open}
                    autoHideDuration={6000}
                    onClose={() => { this.state.open = false; }}>
                    <Alert onClose={() => { this.state.open = false }} severity={this.state.alertType} elevation={6} variant="filled">
                        {this.state.message}
                    </Alert>
                </Snackbar>
                <div className="wave" style={{height:"85%", width:"99%", border:"2px solid #AEAEAE", marginTop:15}}></div>
                <Box style={{height:"14%", width:"100%"}}>
                    <Buttons />
                </Box>
            </Box>
        );
    }
}

export default withStyles(useStyles)(MyPlayer)
